//
//  Utils.swift
//  MedicalBeauty
//
//  Created by Henry on 2018/3/12.
//  Copyright © 2018年 shen_h. All rights reserved.
//

import Foundation
import UIKit

struct Utils {
    
    static func isIphoneX()->Bool{
        if UIScreen.main.bounds.size.height == 812 {	
            return true
        }
        return false
    }
    
    static func isLogined()->Bool{
        if UserDefaults.standard.object(forKey: "token") as? String != nil {
            return true
        }else{
            return false
        }
    }
    
    static func getUserDefaulsFor(key:String) -> Any{
        return UserDefaults.standard.object(forKey: key) as Any
    }
    
    static func instantiateInitialViewControllerWith(storyBoardName:String, identitier:String)->UIViewController{
        return UIStoryboard.init(name: storyBoardName, bundle: nil).instantiateViewController(withIdentifier: identitier);
    }
    
    static func saveSearchHistory(array:[String]){
        let filePath:String = NSHomeDirectory() + "/Documents/Searchhistory.plist"
        (array as NSArray).write(toFile: filePath, atomically: true)
    }
    
//    static func saveShoppingCar(arr:[[String:[String]]]){
//        Utils.theApplication().shoppingCarArray = arr
//        let filePath:String = NSHomeDirectory() + "/Documents/shoppingCar.plist"
//        (arr as NSArray).write(toFile: filePath, atomically: true)
//    }
    
    static func getDictionaryFromJSONString(jsonString:String) ->NSDictionary{
        
        let jsonData:Data = jsonString.data(using: .utf8)!
        
        let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        if dict != nil {
            return dict as! NSDictionary
        }
        return NSDictionary()
        
    }
    
    // MARK:字典转json字符串
    static func getJSONStringFromDictionary(dictionary:NSDictionary) -> String {
        if (!JSONSerialization.isValidJSONObject(dictionary)) {
            print("无法解析出JSONString")
            return ""
        }
        let data : NSData! = try! JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData?
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        return JSONString! as String
        
    }
    
    
    //    MARK:延迟执行
    static func DispatchAfter(after: Double, handler:@escaping ()->())
    {
        DispatchQueue.main.asyncAfter(deadline: .now() + after) {
            handler()
        }
    }
    
    static func setTextFieldPlaceholderColor(textField:UITextField){
        textField.setValue(UIColor.init(hexColor: "#cccccc"), forKeyPath: "_placeholderLabel.textColor")
    }
    
    static func dispatchMainQueue(handler:@escaping ()->()){
        DispatchQueue.main.async {
            handler()
        }
    }
    
    static func labelWith(frame rect:CGRect,font:UIFont,textAlignment:NSTextAlignment,textColor:String,text:String)->UILabel{
        let balance = UILabel.init(frame: rect)
        balance.textColor = UIColor.init(hexColor: textColor)
        balance.textAlignment = textAlignment
        balance.text = text
        balance.font = font
        return balance
    }
    
    static func buttonWith(frame rect:CGRect,font:UIFont,textColor:String,title:String,bgColor:String? = nil)->UIButton{
        let btn = UIButton.init(type: .custom)
        btn.frame = rect
        btn.setTitle(title, for: .normal)
        btn.setTitleColor(UIColor.init(hexColor: textColor), for: .normal)
        btn.titleLabel?.font = font
        if bgColor != nil {
            btn.backgroundColor = UIColor.init(hexColor: bgColor!)
        }
        return btn
    }
    
    static func theApplication()->AppDelegate{
        return UIApplication.shared.delegate as! AppDelegate
    }
    
    
    // MARK:长方形占位图
    static func placeholderImage_c()->UIImage{
        let image = UIImage.init(named: "placeholder_rectangle")
        return (image?.resizableImage(withCapInsets: UIEdgeInsetsMake(20, 20, 20, 20), resizingMode: .stretch))!
    }
    
    static func removeAllUserInfo(){
        UserDefaults.standard.removeObject(forKey: "name")
        UserDefaults.standard.removeObject(forKey: "username")
        UserDefaults.standard.removeObject(forKey: "storeName")
        UserDefaults.standard.removeObject(forKey: "areaId")
        UserDefaults.standard.removeObject(forKey: "address")
        UserDefaults.standard.removeObject(forKey: "storeImg")
        UserDefaults.standard.removeObject(forKey: "licenseImg")
        UserDefaults.standard.removeObject(forKey: "money")
        UserDefaults.standard.removeObject(forKey: "arrears")
        UserDefaults.standard.removeObject(forKey: "areaName")
        UserDefaults.standard.removeObject(forKey: "cityName")
        UserDefaults.standard.removeObject(forKey: "provinceName")
        UserDefaults.standard.removeObject(forKey: "phone")
        UserDefaults.standard.removeObject(forKey: "couponSize")
        UserDefaults.standard.removeObject(forKey: "token")
        UserDefaults.standard.synchronize()
    }
    
    /// 传入秒数获取时分秒
    ///
    /// - Parameter count: 时分秒
    static func getMMSSFromSS(count:Int)->(String,String,String){
        if count < 0 {
            return ("","","")
        }
//        let d = "\(count/24/60/60)"
        
        let h = count/60/60%24
        let m = count/60%60
        let s = count%60
        
        return (String.init(format: "%0.2d", h),String.init(format: "%0.2d", m),String.init(format: "%0.2d", s))
    }
    
    
//    static func shareItem(title:String,url:String,images:[String],shareDetail:String,type:SSDKPlatformType,complete:@escaping ()->()){
//
//        if type == .subTypeQQFriend {
//
//            let isInstall = UIApplication.shared.canOpenURL(URL.init(string: "mqqapi://")!)
//            guard isInstall else {
//                HUD.showText(text: "尚未安装QQ客服端~")
//                return
//            }
//        }else {
//            let isInstall = WXApi.isWXAppInstalled()
//            guard isInstall else {
//                HUD.showText(text: "尚未安装微信客服端~")
//                return
//            }
//        }
//
//        let shareParams = NSMutableDictionary()
//        shareParams.ssdkSetupShareParams(byText: shareDetail, images: images, url: URL.init(string: url), title: title, type: .webPage)
//        ShareSDK.share(type, parameters: shareParams) {  (state : SSDKResponseState, nil, entity : SSDKContentEntity?, error :Error?) in
//
//            switch state {
//
//                case SSDKResponseState.success:
//                    HUD.showText(text: "分享成功")
//                case SSDKResponseState.fail:
//                    print("授权失败,错误描述:\(error as! Error)")
//                    HUD.showText(text: "分享失败")
//                case SSDKResponseState.cancel:
//                    print("操作取消")
//                    HUD.showText(text: "操作取消")
//            default:
//                break
//
//            }
//            complete()
//        }
//    }
    
    static func isIncludeChineseIn(string:String)->Bool {
        for value in string{
            if "\u{4E00}" <= value  && value <= "\u{9FA5}" {
                return true
            }
        }
        return false
    }
    
    
    
    /// 把价格整数位字体变大
    ///
    /// - Parameters:
    ///   - normalString: 原始字符串
    ///   - changeString: 需要改变的价格字符串
    ///   - font: 变大的字体
    /// - Returns:
    static func changeLabelTextFontSize(normalString:String,changeString:String,font:UIFont)->NSAttributedString{
        let attributeString = NSMutableAttributedString.init(string: normalString)
        attributeString.addAttributes([NSAttributedStringKey.font:font], range: NSString.init(string: normalString).range(of: changeString))
        return attributeString
    }
    
    
    /// label 加删除线
    ///
    /// - Parameters:
    ///   - normalString: 原始字符串
    ///   - deleString: 需要添加删除线的字符串
    static func labelTextDeleLine(normalString:String,deleString:String)->NSAttributedString{
        let attributeString = NSMutableAttributedString.init(string: normalString)
        attributeString.addAttributes([NSAttributedStringKey.strikethroughStyle:1], range: NSString.init(string: normalString).range(of: deleString))
        return attributeString
    }
    
    
    /// 字典或者数组 转 JSON
    static func dataTypeTurnJson(element:Any) -> String {
        let jsonData = try! JSONSerialization.data(withJSONObject: element, options: JSONSerialization.WritingOptions.prettyPrinted)
        let str = String(data: jsonData, encoding: String.Encoding.utf8)!
        return str
    }
    
}












